Ext.define('appmod.controller.role.Startup', {
    extend: 'Ext.app.Controller',

    views: [
    	'role.maintain.Dashboard',
		'role.maintain.Form',
		'role.authorization.Form'
    ],

	models : [
		'role.Role',
		'role.Module',
		'role.Menu',
		'role.ModuleFunction'
	],
	
    stores: [
		'role.Paging',
		'role.system.AllAvailable',
		'role.module.List',
		'role.function.List',
		'role.menu.Tree'
	],	

    refs: [
		{ref: 'roleDashboard',selector:'roledashboard'},
		{ref: 'popupWin',selector:'window{isVisible()}'},
		{ref: 'roleForm' , selector:'roleform'},
		{ref: 'authModPanel' , selector:'roleauthorizationform moduleauthorizationpanel'},
		{ref: 'authModFunPanel' , selector:'roleauthorizationform authmodulefunctionlistpanel'},
		{ref: 'roleAuthorizationForm' , selector:'roleauthorizationform'},
		{ref: 'authModuleList', selector:'authmodulelistpanel'},
		{ref: 'menuAuthorization', selector:'roleauthorizationform menuauthorizationpanel'}

	],


    init: function() {
		var me = this;

    	me.control({
			
			'window button[action=closeWin]': {
			    click:me.closeWin
			},

			'roledashboard menuitem[action=addrole]': {
				click:me.showAddingRoleForm
			},
			
			'roledashboard menuitem[action=updaterole]': {
				click:me.showEditingRoleForm
			},

			'roledashboard menuitem[action=deleteroles]': {
				click:me.showDeleteRolesDialog
			},
						
			'roledashboard menuitem[action=modulefunauth]': {
				click:me.showAuthModuleFunctionForm
			},
			
			'moduleauthorizationpanel authmodulelistpanel button[action=auth]': {
				click:me.saveModuleAuth
			},			
			'moduleauthorizationpanel authmodulefunctionlistpanel button[action=auth]': {
				click:me.saveFunctionAuth
			},			
			'menuauthorizationpanel button[action=auth]': {
				click:me.saveMenuAuth
			},
			/*	
			'moduleauthorizationpanel authmodulelistpanel': {
				itemclick:this.clickAndSelectModule
			},
			*/
			'moduleauthorizationpanel authmodulelistpanel': {
				subfunexec:{
					fn:me.clickAndSelectModule,
					scope:me
				}
			},			
			
			'roleauthorizationform tabpanel': {
				tabchange:{
					fn: me.activePanel,
					scope:me
				}
			}

    	});
    },
	
	loadInitComp : function() {
		var mainPanel = Ext.create('appmod.view.role.maintain.Dashboard' , {
			region : 'center',
			border:false,
			padding:'0 0 0 0'
		});
		return mainPanel;		
	},
	
	onLaunch:function(apps) {
		var me = this;
		
		var dsRole = me.getRolePagingStore();
		var roleDashboard = me.getRoleDashboard();
		roleDashboard.bindStore( dsRole );


	},
	
	closeWin:function() {
		var popupWin = this.getPopupWin();
		popupWin.close();
	},
		
	showAddingRoleForm:function() {
		
		var me = this;
		
		var dsSysRole = me.getRoleSystemAllAvailableStore();
		
		var fieldStores = {
			'dsSysRoleId' : dsSysRole
		};
		
		var win = null;
		// --- build new form ---
		if (!win) {
			win = new Ext.create('widget.window', {
				title : '业务角色信息',
				closable : true,
				modal : true,
				width : 450,
				height : 330,
				layout: 'border',
				bodyStytle : 'padding : 5px',
				items:[{
					padding : 5,
					defaults: {
        				labelWidth:65
    				},
					fieldStores:fieldStores,
					xtype : 'roleform',
					region:'center'
				}],
				dockedItems: [{
				    xtype: 'toolbar',
				    dock: 'bottom',
				    ui: 'footer',
				    items: [
						'->',
				        {
            				text: '保 存',
							action:'addRole'
        				},{
            				text: '关 闭',
							action:'closeWin'
        				}
				    ]
				}]	
			});
		}
		
		// --- find form ---
		var form = win.down("roleform");

		var saveBtn = win.down('button[action="addRole"]');
		saveBtn.on("click",me.saveNewRole , me , {
			window : win
		});		
		
		if ( !win.isVisible() ) {
			win.show();
		}		
	},
	
	saveNewRole:function(btn , event , eOpts) {
		var me = this;
		var listView = me.getRoleDashboard();
		var ds = listView.getStore();

		var upWin = eOpts.window;
		
		var formPanel = upWin.down('roleform');
		var win = upWin;
		
		var form = formPanel.getForm();
		form.submit({
			url:'../../data/resource/role/submit_adding.json',
			success:function(form , action) {
				 // --- reflash store ---
				 win.close();
				 
				 ds.load();
				 
				 Ext.Msg.alert('成功', action.result.msg);
			},
			failure: function(form, action){
				switch (action.failureType) {
					case Ext.form.action.Action.CLIENT_INVALID:
						Ext.Msg.alert('失败', '表单里包含错误的信息');
						break;
					case Ext.form.action.Action.CONNECT_FAILURE:
						Ext.Msg.alert('失败', '服务器连接失败,请联系管理人员');
						break;
					case Ext.form.action.Action.SERVER_INVALID:
						Ext.Msg.alert('失败', action.result.msg);
				}
			}
		});		
	},
	
	
	showEditingRoleForm:function() {
		var me = this;
		var defListView = me.getRoleDashboard();	
		var selModel = defListView.getSelectionModel();
		var rec = selModel.getSelection();

		if (rec.length == 0) {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '请先选择一个角色',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});
			return ;
		} else if (rec.length  > 1) {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '只能选择一个角色',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});
			return ;
		}

		var dsSysRole = me.getRoleSystemAllAvailableStore();
		
		var fieldStores = {
			'dsSysRoleId' : dsSysRole
		};
		
		// --- build new form ---
		var win = null;
		if (!win) {
			win = new Ext.create('widget.window', {
				title : '业务角色信息',
				closable : true,
				modal:true,
				width : 450,
				height : 330,
				layout: 'border',
				bodyStytle : 'padding : 5px',
				items:[{
					padding : 5,
					fieldStores:fieldStores,
					defaults: {
        				labelWidth:65
    				},
					xtype : 'roleform',
					region:'center'
				}],
				dockedItems: [{
				    xtype: 'toolbar',
				    dock: 'bottom',
				    ui: 'footer',
				    items: [
						'->',
				        {
            				text: '保 存',
							action:'updateRole'
        				},{
            				text: '清 空',
							action:'reset'
        				}
				    ]
				}]	
			});

		}

		// --- init form data ---
		var formPanel = win.down("roleform");

		var saveBtn = win.down('button[action="updateRole"]');
		saveBtn.on("click",me.saveUpdatedRole , me , {
			window : win
		});

		var form = formPanel.getForm();
		
		form.load({
			params:{
				roleId:rec[0].getId()
			},
			url: '../../data/resource/role/load.json',
            waitMsg: '数据加载中'			
		});
		

		
		if ( !win.isVisible() ) {
			win.show();			
		}			
	},
	
	saveUpdatedRole:function(btn , event , eOpts) {
		var me = this;
		var listView = me.getRoleDashboard();
		var ds = listView.getStore();

		var upWin = eOpts.window;
		
		var formPanel = upWin.down('roleform');
		var win = upWin;
		
		var form = formPanel.getForm();
		form.submit({
			url:'../../data/resource/role/submit_updating.json',
			success:function(form , action) {
				 // --- reflash store ---
				 win.close();
				 
				 ds.load();
				 
				 Ext.Msg.alert('成功', action.result.msg);
			},
			failure: function(form, action){
				switch (action.failureType) {
					case Ext.form.action.Action.CLIENT_INVALID:
						Ext.Msg.alert('失败', '表单里包含错误的信息');
						break;
					case Ext.form.action.Action.CONNECT_FAILURE:
						Ext.Msg.alert('失败', '服务器连接失败,请联系管理人员');
						break;
					case Ext.form.action.Action.SERVER_INVALID:
						Ext.Msg.alert('失败', action.result.msg);
				}
			}
		});			
	},
	
	
	// --- auth module function ---
	showAuthModuleFunctionForm:function() {

		var me = this;
		
		var rolepanel = me.getRoleDashboard();	
		var selModel = rolepanel.getSelectionModel();
		var rec = selModel.getSelection();
		
		if (rec.length == 0) {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '请先选择一个角色',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});
			return ;
		} else if (rec.length  > 1) {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '只能选择一个角色',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});
			return ;
		}
		
		var dsMenuTree = me.getRoleMenuTreeStore();
		var menuProxy = dsMenuTree.getProxy();
		menuProxy.extraParams = {
			roleId:rec[0].getId()
		};
		var stores = {
			'menuTree':dsMenuTree
		};

		
		var win = null;

		// --- build new form ---
		if (!win) {

			win = new Ext.create('widget.window', {
				title : '角色授权视图',
				closable : true,
				modal : true,
				width : 800,
				height : 600,
				layout: 'border',
				bodyStytle : 'padding : 5px',
				items:[{
					padding : 5,
					stores : stores,
					xtype : 'roleauthorizationform',
					region:'center'
				}]
			});
		}

		// --- get all panel ---
		var roleAuthTabPanels = win.down('roleauthorizationform tabpanel');
		
		// --- binding store ---
		var activeTabPanel = roleAuthTabPanels.getActiveTab();
		
		var dsOfAuthMods = me.getRoleModuleListStore();
		var authModPanel = win.down('roleauthorizationform moduleauthorizationpanel');
		authModPanel.bindModuleStore( dsOfAuthMods );
		
		var dsOfAuthModFuns = me.getRoleFunctionListStore();
		authModPanel.bindFunctionStore(dsOfAuthModFuns);
		
		var modulelistPanels = activeTabPanel.query('authmodulelistpanel'); 
		if (modulelistPanels[0]) {
			var modulelistStore = modulelistPanels[0].getStore();
			var moduleProxy = modulelistStore.getProxy();
			moduleProxy.extraParams = {
				roleId:rec[0].getId()
			};
			modulelistStore.load();
			
		}



		// --- load  object ---
		var roleauthorizationform = me.getRoleAuthorizationForm();		 
		var basicForm = roleauthorizationform.getForm();
		if ( rec.length == 1 ) {
			basicForm.setValues({
				roleName:rec[0].get('name'),
				roleId:rec[0].getId()
			});
		}
	
		if ( !win.isVisible() ) {
			win.show();
		} 
		
	},
	
	showDeleteRolesDialog:function() {
		var me = this;
		
		var defListView = me.getRoleDashboard();	
		var selModel = defListView.getSelectionModel();
		var rec = selModel.getSelection();


		if (rec.length == 0) {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '请先选择一个角色',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});
			return ;
		}
		
		// --- select resource --
		var removeRecs = "";
		for (var i = 0 ; i < rec.length ; i++) {
			if (removeRecs.length != 0 ) {
				removeRecs += ",";
			}
			removeRecs += rec[i].get('name');
		}
		
		Ext.MessageBox.confirm('确认', '肯定要删除角色: "'+removeRecs+'"?',me.confirmDeletedRoles , me);		
	},
	
	confirmDeletedRoles:function(confirm) {
		var me = this;
		
		var defListView = me.getRoleDashboard();	
		var selModel = defListView.getSelectionModel();
		var rec = selModel.getSelection();
		
		if (confirm == "no") {
			return;
		}

		var jsonObj = [];
		for (var i = 0 ; i < rec.length ; i++) {
			jsonObj.push(rec[i].getId());
		}

		
		// --- update record using ajax
		try {

			Ext.Ajax.request({
				url: '../../data/resource/role/submit_deleteall.json',
				method:'post',
				/*
				params:{
					'jsonData':Ext.encode(jsonObj)
				},
				*/
				jsonData:jsonObj,
				success: function(response, opts) {

					var listView = me.getRoleDashboard();
					// --- update load ---
					listView.getStore().load();
										 
     				var obj = Ext.decode(response.responseText);
					 
					 // --- popup message ---
					Ext.MessageBox.show({
        				title: "提示",
        				msg: obj.msg,
        				buttons: Ext.MessageBox.OK,
        				icon: Ext.MessageBox.WARNING
       				});
					
					// --- reload ---

				},
				failure: function(response, opts) {
				
				}
			});

			
		} catch (e) {
			alert(e);
		}	
		
	},
	

	activePanel:function(tabPanel, newCard, oldCard, eOpts) {
		var me = this;
		var basicForm = me.getRoleAuthorizationForm().getForm();
		var formInfo = basicForm.getValues();

		var currentXtype = newCard.getXType();

		// --- binding and load store
		if ( currentXtype == 'menuauthorizationpanel') {
			var store = newCard.getStore();
			store.setRootNode({
				expanded:false
			});
			var menuStoreProxy = store.getProxy();
			menuStoreProxy.extraParams = {
				roleId:formInfo.roleId
			};
			//store.reload();
			/*
			store.load();
			*/
		}
		else if (currentXtype == 'moduleauthorizationpanel') {
			
			var modPanel = newCard.down('authmodulelistpanel');
			var store = modPanel.getStore();
			store.load();

		}
		

	},
	
	
	saveMenuAuth:function() {
		var me = this;
		var authMenu = me.getMenuAuthorization();
		var store = authMenu.getStore();

		var proxy =store.getProxy();
		store.sync({
			callback:function(batch , options) {
				//alert('callback');
			},
			success:function(batch , options) {
				if ( batch.isComplete) {
					Ext.MessageBox.show({
        				title: "提示",
        				msg: '菜单授权更新成功',
        				buttons: Ext.MessageBox.OK,
        				icon: Ext.MessageBox.WARNING
       				});
				}
			},
			failure:function(batch , options) {
				//alert('failure');
			}
		});

	},
	
	clickAndSelectModule:function(self, record, item, index, eveObj) {

		var me = this;
		var recId = null;
		if (record.getId) {
			recId = record.getId();
		} else {
			recId = record.get('id');
		}

		var basicForm = me.getRoleAuthorizationForm().getForm();

		var formInfo = basicForm.getValues();
		
		// --- get another panel store ---
		var functionPanel = me.getAuthModFunPanel();
		var funPanelStore = functionPanel.getStore();
		
		var proxy = funPanelStore.getProxy();

		proxy.extraParams = {
			modResId : recId,
			roleId : formInfo['roleId']
		};

		funPanelStore.load();
				
	},
	
	saveFunctionAuth:function() {
		
		var me = this;

		// --- check the current status ---
		var authModList = me.getAuthModuleList();
		var selModel = authModList.getSelectionModel();
		var recs = selModel.getSelection();

		var modAcl = recs[0].get("acl");
		if (modAcl == "deny") {
			Ext.MessageBox.show({
        		title: "提示",
        		msg: '当前所选模块禁止访问，所属功能均不能保存记录!',
        		buttons: Ext.MessageBox.OK,
        		icon: Ext.MessageBox.WARNING
       		});
			return ;			
		}

		var authModFunList = me.getAuthModFunPanel();
		var store = authModFunList.getStore();

		var proxy =store.getProxy();
				
		store.sync({
			callback:function(batch , options) {
				//alert('callback');
			},
			success:function(batch , options) {
				if ( batch.isComplete) {
					Ext.MessageBox.show({
        				title: "提示",
        				msg: '模块功能授权更新成功',
        				buttons: Ext.MessageBox.OK,
        				icon: Ext.MessageBox.WARNING
       				});
				}
			},
			failure:function(batch , options) {
				//alert('failure');
			}
		});		
	},
	
	saveModuleAuth:function(myself, event) {
		var me = this;

		var authModList = me.getAuthModuleList();
		var store = authModList.getStore();

		var proxy =store.getProxy();

		store.sync({
			callback:function(batch , options) {
				//alert('callback');
			},
			success:function(batch , options) {
				if ( batch.isComplete) {
					Ext.MessageBox.show({
        				title: "提示",
        				msg: '模块授权更新成功',
        				buttons: Ext.MessageBox.OK,
        				icon: Ext.MessageBox.WARNING
       				});
				}
			},
			failure:function(batch , options) {
				//alert('failure');
			}
		});


		var basicForm = me.getRoleAuthorizationForm().getForm();

		var formInfo = basicForm.getValues();

/*
		var modulelistStore = this.getAuthmodulelistpanel().getStore();

		var moduleSelModel = this.getAuthmodulelistpanel().getSelectionModel();

		var modulefunctionlistStore = this.getAuthModuleFunctionList().getStore();
		
		var jsonObj = {
			role:formInfo
		};
		
		// ---- count  module record ---
		var moduleRecs = moduleSelModel.getSelection();

		for (var i = 0 ; i < moduleRecs.length ; i++) {
			var access = moduleRecs[i].get('access');
			var modRes = {
				id : moduleRecs[i].getId(),
				access : access
			};
			jsonObj.mod = modRes;			
		}
		
		var updateFunctions = [];	
		for (var j = 0 ; j <  modulefunctionlistStore.getCount() ; j++) {
			var funRec = modulefunctionlistStore.getAt(j);
			var funRes = {
				id : funRec.getId(),
				access : funRec.get('access')
			}
			updateFunctions.push(funRes);
		}
		jsonObj.func = updateFunctions;
		
		// --- update record using ajax
		try {

			Ext.Ajax.request({
				url: '../data/resource/modulefunction_auth.json',
				method:'post',
				params:{
					'jsonData':Ext.encode(jsonObj)
				},
				success: function(response, opts) {
					 
					 var obj = Ext.decode(response.responseText);
					 
					 // --- popup message ---
					Ext.MessageBox.show({
        				title: "提示",
        				msg: obj.msg,
        				buttons: Ext.MessageBox.OK,
        				icon: Ext.MessageBox.WARNING
       				});
					
					// --- reload ---

				},
				failure: function(response, opts) {
				
				}
			});

			
		} catch (e) {
			alert(e);
		}	
		*/
	}
		
	

	
});